import React, { useState, useEffect } from 'react';
import { Layout, Button, theme, Image } from 'antd';
import Icon, { DownloadOutlined, CheckOutlined, CloseOutlined } from '@ant-design/icons';

const { Header, Content } = Layout;

function requestImagesFromContentJs(message, callback) {
  chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
    if (callback && tabs.length) {
      chrome.tabs.sendMessage(tabs[0].id, message, function (response) {
        if (chrome.runtime.lastError) {
        } else {
          callback(response);
        }
      });
    }
  });
}


function App() {
  const [images, setImages] = useState([])
  const [selected, setSelected] = useState([])

  useEffect(() => {
    setSelected(new Array(images.length).fill(false))
  }, [images])

  useEffect(() => {
    requestImagesFromContentJs({ action: 'query-images' }, function (response) {
      setImages(response)
    });
  }, [])

  const {
    token: { colorBgContainer, borderRadiusLG },
  } = theme.useToken();

  function toggle(index) {
    return (e) => {
      let s = Object.assign([], selected)
      s[index] = !s[index];
      setSelected(s);
    }
  }
  function selectAllOrNone(acion) {
    return (e) => {
      if (acion == 'all') {
        setSelected(new Array(images.length).fill(true))
      } else {
        setSelected(new Array(images.length).fill(false))
      }
    }
  }

  function download_selected() {
    images.forEach((url, idx) => {
      if (selected[idx]) {
        chrome.downloads.download({
          url: url,
        })
      }
    })
  }


  return (
    <Layout>
      <Header
        style={{
          position: 'sticky',
          top: 0,
          zIndex: 1,
          width: '100%',
          display: 'flex',
          alignItems: 'center',
          background: '#eaeaea',
          minWidth: '600px'
        }}
      >
        <span>选 中： {selected.filter(Boolean).length}/{selected.length}</span>
        {
          selected.filter(Boolean).length == selected.length
            ? <Button type="dashed" style={{ position: 'absolute', right: '15px' }} icon={<CloseOutlined />} onClick={selectAllOrNone('none')}>反 选</Button>
            : <Button type="primary" style={{ position: 'absolute', right: '15px' }} icon={<CheckOutlined />} onClick={selectAllOrNone('all')}>全 选</Button>
        }
      </Header>
      <Content style={{ padding: '0 10px' }}>
        <div
          style={{
            padding: 4,
            minHeight: 380,
            background: colorBgContainer,
            borderRadius: borderRadiusLG,
          }}
        >

          {images.map((url, idx) => {
            return selected[idx]
              ? <Image
                style={{ border: '10px solid #155dff', borderRadius: '10px' }}
                preview={false}
                width='25%'
                key={idx}
                src={url}
                onClick={toggle(idx)}
              />
              : <Image
                preview={false}
                width='25%'
                key={idx}
                src={url}
                onClick={toggle(idx)}
              />
          })}
        </div>
      </Content>
      <div style={{ position: 'fixed', bottom: '20px', right: '15px' }}>
        <Button type="primary" icon={<DownloadOutlined />} onClick={download_selected}>下 载</Button>
      </div>
    </Layout >
  );
};

export default App;